package com.mud.dnd.frontend.rs;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.Response.Status;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.jboss.resteasy.plugins.providers.multipart.InputPart;
import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;

import com.mud.dnd.domain.common.DAOException;
import com.mud.dnd.ejb.PictureManager;
import com.mud.dnd.ejb.common.AuthenticationException;
import com.mud.dnd.frontend.rs.common.DnDJSONResponse;
import com.mud.dnd.frontend.rs.common.DnDJSONResponse.ResponseSatus;


@Stateless
@Path("/GameItem/Picture")
public class PictureJSONService {
	
	@EJB
	private PictureManager picManager;
	
	
	@GET
	@Path("/getPic")
    @Produces(MediaType.MULTIPART_FORM_DATA)
	public Response downloadPicForGameItem(@QueryParam("gameItemID") int gameItemID) {
 
		String filePath;
		File file = null;
		
		try {
			filePath = picManager.getPicture(gameItemID);
			
			if(filePath!=null && (!filePath.equals("")))
			{
				file = new File(filePath);
			}else
			{
				ResponseBuilder response = Response.status(Status.NOT_FOUND);
				return response.build();
			}
			
			
		} catch (DAOException e) {
			ResponseBuilder response = Response.status(Status.NOT_FOUND);
			return response.build();
		}
		
		
		
		 
		ResponseBuilder response = Response.ok((Object) file);
		response.header("Content-Disposition",
			"attachment; filename=image_from_server.png");
		return response.build();
 
	}
	
	
	
	
	@GET
	@Path("/getAllPic")
    @Produces(MediaType.MULTIPART_FORM_DATA)
	public Response downloadAllPic() {
 
		File file = null;

		try {
			file = picManager.getAllPicture();

			
		} catch (IOException e) {
			ResponseBuilder response = Response.status(Status.NOT_FOUND);
			return response.build();
		}
		
		 
		ResponseBuilder response = Response.ok((Object) file);
		response.header("Content-Disposition",
			"attachment; filename=allPics.zip");
		return response.build();
 
	}
	
	
	
	@POST
	@Path("/uploadPic")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
	public DnDJSONResponse uploadPicToGameItem(MultipartFormDataInput input ,@QueryParam("gameItemID") int gameItemID,@QueryParam("userName")String userName,@QueryParam("sessionID")String sessionID) {
 
		String fileName = "";
 
		Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
		List<InputPart> inputParts = uploadForm.get("image");
 
		for (InputPart inputPart : inputParts) {
 
		 try {
 
			MultivaluedMap<String, String> header = inputPart.getHeaders();
			String fileExtension = FilenameUtils.getExtension(getFileName(header));
			fileName= "../pictures/picture"+gameItemID+"."+fileExtension;
 
			//convert the uploaded file to inputstream
			InputStream inputStream = inputPart.getBody(InputStream.class,null);
 
			byte [] bytes = IOUtils.toByteArray(inputStream);
			/*if(bytes.length > 256*1024)
			{

				return new DnDJSONResponse(ResponseSatus.ERROR, "The picture is too large!");
			}*/
 
			//constructs upload file path
			//fileName = UPLOADED_FILE_PATH + fileName;
 
			
			picManager.addPicture(fileName,bytes,  gameItemID,userName, sessionID);
 
 
		  } catch (IOException e) {
			  return new DnDJSONResponse(ResponseSatus.ERROR, "Error occured during uploading the picture!");
		  } catch (DAOException e) {
			  return new DnDJSONResponse(ResponseSatus.ERROR, "Error occured during uploading the picture!");
		} catch (AuthenticationException e) {
			 return new DnDJSONResponse(ResponseSatus.ERROR, "Authentication required!");
		}
 
		}

		return new DnDJSONResponse( DnDJSONResponse.ResponseSatus.OK );
 
	}
 
	/**
	 * header sample
	 * {
	 * 	Content-Type=[image/png], 
	 * 	Content-Disposition=[form-data; name="file"; filename="filename.extension"]
	 * }
	 **/
	//get uploaded filename, is there a easy way in RESTEasy?
	private String getFileName(MultivaluedMap<String, String> header) {
 
		String[] contentDisposition = header.getFirst("Content-Disposition").split(";");
 
		for (String filename : contentDisposition) {
			if ((filename.trim().startsWith("filename"))) {
 
				String[] name = filename.split("=");
 
				String finalFileName = name[1].trim().replaceAll("\"", "");
				return finalFileName;
			}
		}
		return "unknown";
	}
 
	

}
